<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert
        title="添加商品的消息"
        type="info"
        show-icon
        center
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="Number(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单 -->
      <el-form
        :model="addGoodInfo"
        :rules="addGoodInforules"
        ref="addGoodInfoForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="leaveTab"
          @tab-click="clickTab"
        >
          <el-tab-pane label="基本信息" name="0">
            <template>
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoodInfo.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input v-model="addGoodInfo.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="addGoodInfo.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model="addGoodInfo.goods_number"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader
                  v-model="selectedCateId"
                  :options="cateList"
                  :props="cascaderProps"
                  @change="cascaderChange"
                ></el-cascader>
              </el-form-item>
            </template>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="(mb, i) of manyTableList"
              :key="i"
              :label="mb.attr_name"
            >
              <el-checkbox-group v-model="mb.attr_vals">
                <el-checkbox
                  :label="val"
                  v-for="(val, i) of mb.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="(ob, i) of onlyTableList"
              :key="i"
              :label="ob.attr_name"
            >
              <el-input v-model="ob.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              list-type="picture"
              :headers="headersUpload"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="addGoodInfo.goods_introduce"/>
            <el-button class="addP-btn" type="primary" @click="addPro">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewImgVisible" width="30%">
      <div class="previewImg"><img :src="previewImgPath" alt="" /></div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      previewImgPath: "",
      previewImgVisible: false,
      // 上传图片的头部
      headersUpload: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      onlyTableList: [],
      checkedvals: [],
      manyTableList: [],
      // 级联选择器的数据
      selectedCateId: [],
      cateList: [],
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
      },
      activeIndex: "0",
      addGoodInfo: {
        goods_name: "",
        goods_price: '',
        goods_weight: "",
        goods_number: '1',
        // 上传文件图片
        pics: [],
        goods_introduce:'',
        goods_cat:'',
        attrs:[]
      },
      addGoodInforules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //   添加商品
    async addPro(){
        this.addGoodInfo.goods_cat=this.selectedCateId.join()
        // 没有点击其他页面就会获得空数组
        if(this.onlyTableList.length==0||this.manyTableList.length==0)return this.$message.error('商品信息不完整')
        this.getAttr(this.manyTableList)
        this.getAttr(this.onlyTableList)
        console.log(this.addGoodInfo)
        let {data:res}=await this.$axios.post('/goods',this.addGoodInfo).catch(err=>console.log(err))
        if(res.meta.status!=201)return this.$message.error("添加商品失败")
        this.$message.success("添加商品成功")
        this.$router.push('/goods')
    },
    // 封装属性和参数获取的方法
    getAttr(arr){
        arr.forEach(el=>{
            if(typeof el.attr_vals!=='string'){
                el.attr_vals=el.attr_vals.join(',')
            }
            let newObj={attr_id:el.attr_id,attr_value:el.attr_vals}
            this.addGoodInfo.attrs.push(newObj)
        })
    },
    //   图片预览
    handlePreview(file) {
      let path = file.response.data.url;
      this.previewImgPath = path;
      this.previewImgVisible = true;
    },
    //   图片移除
    handleRemove(file) {
      let path = file.response.data.tmp_path;
      let i = this.addGoodInfo.pics.findIndex((el) => el.pic == path);
      this.addGoodInfo.pics.splice(i, 1);
      console.log(this.addGoodInfo.pics);
    },
    //   图片上传成功
    uploadSuccess(file) {
      let picInfo = { pic: '/'+file.data.tmp_path };
      this.addGoodInfo.pics.push(picInfo);
      console.log(this.addGoodInfo.pics);
    },
    //   级联选择器事件
    cascaderChange() {
      if (this.selectedCateId.length != 3) {
        this.selectedCateId = [];
      }
    },
    async clickTab(){
        console.log(this.activeIndex)
          //   进入第二个标签页加载数据
        if (this.activeIndex == 1) {
          let { data: res } = await this.$axios.get(
            `categories/${this.selectedCateId[2]}/attributes`,
            { params: { sel: "many" } }
          );
          if (res.meta.status != 200)
            return this.$message.error("获取数据失败");
          res.data.forEach((el) => {
            el.attr_vals.length == 0
              ? (el.attr_vals = [])
              : (el.attr_vals = el.attr_vals.split(","));
          });
          this.manyTableList = res.data;
        }
        //   进入第三个标签
        if (this.activeIndex == 2) {
          let { data: res } = await this.$axios.get(
            `categories/${this.selectedCateId[2]}/attributes`,
            { params: { sel: "only" } }
          );
          if (res.meta.status != 200)
            return this.$message.error("获取数据失败");
          this.onlyTableList = res.data;
        }
        console.log(this.addGoodInfo)
    },
    //   离开一个标签页进行判断
    leaveTab(activeName, oldActiveName) {
        // 第一个标签页进入其他标签页
        if (oldActiveName == 0) {
          let validres;
          this.$refs.addGoodInfoForm.validate((valid) => {
            validres = valid;
          });
          if (!validres || this.selectedCateId.length != 3) {
            this.$message.error("基本信息填写不完整");
            return false
          }
        }
    },
    //   获取级联选择器的数据
    async getCateList() {
      let { data: res } = await this.$axios.get("categories");
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      this.cateList = res.data;
    },
  },
  created() {
    this.getCateList();
  },
};
</script>
<style lang="less" scoped>
.demo-ruleForm {
  margin-top: 20px;
}
.el-steps {
  margin-top: 20px;
}
.el-checkbox {
  margin: 0 20px 0 0 !important;
}
.previewImg {
  width: 100%;
  height: 100%;
  img {
    width: 100%;
    height: 100%;
  }
}
.addP-btn{
    margin-top:20px
}
</style>